package guda.house.web.action.sys.admin;

import guda.grape.autogen.common.page.BizResult;
import guda.grape.util.RequestUtil;
import guda.house.biz.AdminBiz;
import guda.house.biz.form.AdminVillageForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * Created by well on 15/11/9.
 */
@Controller
public class BindVillageAction {

    @Autowired
    private AdminBiz adminBiz;

    @RequestMapping(value = "sys/admin/bindVillage/create.htm", method = RequestMethod.GET)
    public String create(HttpServletRequest request, ModelMap modelMap,AdminVillageForm adminVillageForm, BindingResult result) {
        long adminId = RequestUtil.getLong(request,"id");
        adminVillageForm.setAdminId(adminId);
        BizResult bizResult = adminBiz.queryAllVillage(adminId);
        modelMap.putAll(bizResult.data);
        return "sys/admin/bindVillage/create.vm";

    }

    @RequestMapping(value = "sys/admin/bindVillage/doSave.htm", method = RequestMethod.POST)
    public String doSave(HttpServletRequest request, ModelMap modelMap,@Valid AdminVillageForm adminVillageForm, BindingResult result) {
        if(result.hasErrors()){
            BizResult bizResult = adminBiz.queryAllVillage(adminVillageForm.getAdminId());
            modelMap.putAll(bizResult.data);
            return "sys/admin/bindVillage/create.vm";
        }
        BizResult bizResult = adminBiz.bindVillage(adminVillageForm);
        modelMap.putAll(bizResult.data);

        if (bizResult.success) {
            return "redirect:/sys/admin/list.htm";
        } else {
            return "redirect:/error.htm?code="+bizResult.code;
        }

    }
}
